package cn.texous.util.commons.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 对比工具
 *
 * @author Showa.L
 * @since 2019/11/26 18:15
 */
public class DiffUtils {

    public  <O, N> Boolean diff2List(List<O> oList, List<N> nList,
                                     BiFunction<O, N, Boolean> compareFunction,
                                     BiFunction<O, N, O> updateFunction,
                                     Consumer<Collection<O>> deleteConsumer,
                                     Consumer<Collection<N>> insertConsumer,
                                     Consumer<Collection<O>> updateConsumer) {

        List<O> needDelete = Lists.newArrayList(oList);
        List<N> needAdd = Lists.newArrayList(nList);
        List<N> inUpdate = Lists.newArrayList();
        List<O> needUpdate = Lists.newArrayList();
        for (O o : oList) {
            boolean update = false;
            for (N n : nList) {
                if (compareFunction.apply(o, n)) {
                    update = true;
                    inUpdate.add(n);
                    needUpdate.add(updateFunction.apply(o, n));
                }
            }
            if (!update)
                needDelete.add(o);
        }
        needAdd.removeAll(inUpdate);
        if (CollectionUtils.isNotEmpty(needDelete))
            deleteConsumer.accept(needDelete);
        if (CollectionUtils.isNotEmpty(needAdd))
            insertConsumer.accept(needAdd);
        if (CollectionUtils.isNotEmpty(needUpdate))
            updateConsumer.accept(needUpdate);

        return true;

    }

}
